package com.marver.shiro;

import com.marver.common.Global;
import com.marver.common.utils.JedisUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @description: redis shiro session dao
 * @Author: Marver
 * @date: 2018-04-25 18:24
 **/
@Component
public class RedisShiroSessionDao extends EnterpriseCacheSessionDAO {

    //创建session
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        final String key = Global.shiroSessionKey+sessionId;
        setShiroSession(key,session);
        return sessionId;
    }

    //读取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if(session == null){
            final String key = Global.shiroSessionKey+sessionId;
            session = getShiroSession(key);
        }
        return session;
    }

    //更新session
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        final String key = Global.shiroSessionKey+session.getId();
        setShiroSession(key,session);
    }

    //删除session
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        final String key = Global.shiroSessionKey+session.getId();
        JedisUtils.del(key);
    }

    private Session getShiroSession(String key) {
        return (Session)JedisUtils.getObject(key);
    }

    private void setShiroSession(String key, Session session){
        //60分钟过期
        JedisUtils.setObject(key, session,3600);
    }
}
